/*
 * @(#)WorkflowPermissionSetupTag.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.taglib;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.util.RequestUtils;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.Utility;
import com.dcivision.framework.taglib.TagUtil;
import com.dcivision.framework.taglib.html.FormTag;
import com.dcivision.framework.web.WebUtil;
import com.dcivision.user.bean.UserGroup;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.bean.UserRole;
import com.dcivision.user.dao.UserGroupDAObject;
import com.dcivision.user.dao.UserRecordDAObject;
import com.dcivision.user.dao.UserRoleDAObject;
import com.dcivision.workflow.bean.MtmWorkflowDynamicUserActor;
import com.dcivision.workflow.bean.MtmWorkflowStepUserActor;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.bean.WorkflowStep;
import com.dcivision.workflow.core.WorkflowRetrievalManager;
import com.dcivision.workflow.dao.MtmWorkflowDynamicUserActorDAObject;
import com.dcivision.workflow.dao.WorkflowProgressDAObject;

/**
 WorkflowPermissionSetupTag.java

 @author      Lun Au
 @company     DCIVision Limited
 @creation date   2005/3/2
 @version     $Revision: 1.23.2.10 $
 */
public class WorkflowPermissionSetupTag extends BodyTagSupport {
  public static final String REVISION = "$Revision: 1.23.2.10 $";

  private static final transient String DELIMITER_FIELD = "\t";
  private static final transient String DELIMITER_ENTRY = "\n";

  protected Log log = LogFactory.getLog(this.getClass().getName());

  protected SessionContainer sessionContainer;
  protected String contextPath;

  private String permissionType = "";
  private String labelPrefix = "common.permission.label_";
  private boolean enableOthers = false;

  private String userListName = "userRecords";
  private String groupListName = "userGroups";
  private String roleListName = "userRoles";
  private String actorListName = "actorTypes";

  private String postFix = null;
  private String isAssignOwner = null;
  private String ownerLimit = "";

  private boolean showPermissionTitle = true;

  
  public WorkflowPermissionSetupTag(){
    super();
  }

  /**
   * @return Returns the labelPrefix.
   */
  public String getLabelPrefix() {
    return labelPrefix;
  }

  /**
   * @param labelPrefix The labelPrefix to set.
   */
  public void setLabelPrefix(String labelPrefix) {
    this.labelPrefix = labelPrefix;
  }

  /**
   * @return Returns the permissionType.
   */
  public String getPermissionType() {
    return permissionType;
  }

  /**
   * @param permissionType The permissionType to set.
   */
  public void setPermissionType(String permissionType) {
    this.permissionType = permissionType;
  }

  /**
   * @return Returns the enableOthers.
   */
  public boolean isEnableOthers() {
    return enableOthers;
  }
  /**
   * @param enableOthers The enableOthers to set.
   */

  public void setEnableOthers(boolean enableOthers) {
    this.enableOthers = enableOthers;
  }



  /**
   * @return Returns the userListName.
   */
  public String getUserListName() {
    return userListName;
  }

  /**
   * @param userListName The userListName to set.
   */
  public void setUserListName(String userListName) {
    this.userListName = userListName;
  }

  /**
   * @return Returns the actorListName.
   */
  public String getActorListName() {
    return actorListName;
  }

  /**
   * @param actorListName The actorListName to set.
   */
  public void setActorListName(String actorListName) {
    this.actorListName = actorListName;
  }

  /**
   * @return Returns the groupListName.
   */
  public String getGroupListName() {
    return groupListName;
  }

  /**
   * @param groupListName The groupListName to set.
   */
  public void setGroupListName(String groupListName) {
    this.groupListName = groupListName;
  }

  /**
   * @return Returns the roleListName.
   */
  public String getRoleListName() {
    return roleListName;
  }

  /**
   * @param roleListName The roleListName to set.
   */
  public void setRoleListName(String roleListName) {
    this.roleListName = roleListName;
  }

  /**
   * @return Returns the isAssignOwner.
   */
  public String getIsAssignOwner() {
    return isAssignOwner;
  }

  /**
   * @param isAssignOwner The isAssignOwner to set.
   */
  public void setIsAssignOwner(String isAssignOwner) {
    this.isAssignOwner = isAssignOwner;
  }

  /**
   * @return Returns the postFix.
   */
  public String getPostFix() {
    return postFix;
  }

  /**
   * @param postFix The postFix to set.
   */
  public void setPostFix(String postFix) {
    this.postFix = postFix;
  }

  public String getOwnerLimit() {
    return ownerLimit;
  }

  public void setOwnerLimit(String ownerLimit) {
    this.ownerLimit = ownerLimit;
  }

  /**
   * 
   * @return
   */
  public boolean isShowPermissionTitle() {
    return showPermissionTitle;
  }

  /**
   * decide wether show permission user(s) title
   * @param showPermissionTitle
   */
  public void setShowPermissionTitle(boolean showPermissionTitle) {
    this.showPermissionTitle = showPermissionTitle;
  }
  
  public int doStartTag() throws JspException {
    try {
      init();
      pageContext.getOut().print( this.getContent() );
    } catch (ApplicationException ae){
      log.error(ae.getMsgCode(), ae);
    } catch (Exception e) {
      log.fatal(e.getMessage(), e);
    } finally {
      this.release();
    }
    return(SKIP_BODY);
  }

  public int doEndTag() throws JspException {
    return EVAL_PAGE;
  }

  public void release() {
    super.release();
  }

  protected boolean validateTag(){
    //return ( stepID!=null || (userActorList!=null&&filterBy!=null) );
    return true;
  }

  protected String getContent() throws ApplicationException {
    StringBuffer sb = new StringBuffer();
    FormTag formTag = (FormTag)BodyTagSupport.findAncestorWithClass(this, FormTag.class);
    JspWriter out = pageContext.getOut();
    try{
      Connection conn = (Connection)pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY);
      UserRecordDAObject userRecordDAObject = new UserRecordDAObject(sessionContainer, conn);
      UserGroupDAObject userGroupDAObject = new UserGroupDAObject(sessionContainer, conn);
      UserRoleDAObject userRoleDAObject = new UserRoleDAObject(sessionContainer, conn);
      MtmWorkflowDynamicUserActorDAObject dynamicUserActorDAO = new MtmWorkflowDynamicUserActorDAObject(sessionContainer, conn);



      List allUserList=new LinkedList() ;
      List allGroupList=new LinkedList();
      List allRoleList=new LinkedList();
      List allOtherList =new LinkedList();
      if (Utility.isEmpty(this.isAssignOwner)) {
        allUserList = userRecordDAObject.getFullList();
        allGroupList = userGroupDAObject.getFullList();
        allRoleList = userRoleDAObject.getFullList();
        allOtherList = new ArrayList();
      } else{
        WorkflowProgressDAObject pdao =new WorkflowProgressDAObject(sessionContainer, conn);
        WorkflowProgress progress=(WorkflowProgress)pdao.getObjectByID(new Integer(this.postFix) );
        HashMap roleMap=(HashMap)pageContext.getRequest().getAttribute("userRoleListMap");
        HashMap userMap=(HashMap)pageContext.getRequest().getAttribute("userListMap");
        HashMap groupListMap=(HashMap)pageContext.getRequest().getAttribute("userGroupListMap");

        allRoleList=(List)roleMap.get(progress.getWorkflowStepID());
        allUserList=(List)userMap.get(progress.getWorkflowStepID());
        allGroupList=(List)groupListMap.get(progress.getWorkflowStepID());

      }

      if ( !Utility.isEmpty((String)pageContext.getRequest().getAttribute(userListName)) ) {
        userListName = (String)pageContext.getRequest().getAttribute(userListName);
      }

      if ( !Utility.isEmpty((String)pageContext.getRequest().getAttribute(groupListName)) ) {
        groupListName = (String)pageContext.getRequest().getAttribute(groupListName);
      }

      if ( !Utility.isEmpty((String)pageContext.getRequest().getAttribute(roleListName)) ) {
        roleListName = (String)pageContext.getRequest().getAttribute(roleListName);
      }

      if ( !Utility.isEmpty((String)pageContext.getRequest().getAttribute(actorListName)) ) {
        actorListName = (String)pageContext.getRequest().getAttribute(actorListName);
      }
      String userRecords[] = new String[0];
      String userGroups[] = new String[0];
      String userRoles[] = new String[0];
      String actorTypes[] = new String[0];
      if (!Utility.isEmpty(this.isAssignOwner)) {
        List userRecordList = new ArrayList(), userGroupList = new ArrayList(), userRoleList = new ArrayList();
        List userActorList = dynamicUserActorDAO.getListByWorkflowProgressID(new Integer(this.postFix));
        List actorTypeList = new ArrayList();
        log.debug("step user actor list: "+userActorList.size());
        for (int i=0; i<userActorList.size(); i++) {
          MtmWorkflowDynamicUserActor dynamicActor = (MtmWorkflowDynamicUserActor) userActorList.get(i);
          log.debug("current actor type: " + dynamicActor.getActorType());
          if (MtmWorkflowStepUserActor.ACTOR_TYPE_USER.equals(dynamicActor.getActorType()) ) { //* current actor is a user account
            userRecordList.add(dynamicActor.getActorID().toString() + "_" + dynamicActor.getPermission());
          } else if (MtmWorkflowStepUserActor.ACTOR_TYPE_GROUP.equals(dynamicActor.getActorType()) ) { //* current actor is an user group
            userGroupList.add(dynamicActor.getActorID().toString() + "_" + dynamicActor.getPermission());
          } else if (MtmWorkflowStepUserActor.ACTOR_TYPE_ROLE.equals(dynamicActor.getActorType()) ) { //* current actor is an user role
            userRoleList.add(dynamicActor.getActorID().toString() + "_" + dynamicActor.getPermission());
          } else if (MtmWorkflowStepUserActor.ACTOR_TYPE_SUBMITTER.equals(dynamicActor.getActorType())
              || MtmWorkflowStepUserActor.ACTOR_TYPE_EVERYONE.equals(dynamicActor.getActorType())
              || MtmWorkflowStepUserActor.ACTOR_TYPE_REPORT_TO.equals(dynamicActor.getActorType())
              || MtmWorkflowStepUserActor.ACTOR_TYPE_RECURSIVE_RUNTIME_ASSIGN.equals(dynamicActor.getActorType())
              || MtmWorkflowStepUserActor.ACTOR_TYPE_PREVIOUS_TASK_OWNER.equals(dynamicActor.getActorType())
              || MtmWorkflowStepUserActor.ACTOR_TYPE_PREVIOUS_TASK_ACTION_TAKER.equals(dynamicActor.getActorType())
              || MtmWorkflowStepUserActor.ACTOR_TYPE_REPORT_TO_OF_PREVIOUS_TASK_ACTION_TAKER.equals(dynamicActor.getActorType())
              || MtmWorkflowStepUserActor.ACTOR_TYPE_ACTION_TAKER.equals(dynamicActor.getActorType())
              || MtmWorkflowStepUserActor.ACTOR_TYPE_REPORT_TO_OF_ACTION_TAKER.equals(dynamicActor.getActorType())
          )  {//* current actor is special actor type
            log.debug("special actor type found!!!!!!!!!!");
            if( MtmWorkflowStepUserActor.ACTOR_TYPE_ACTION_TAKER.equals(dynamicActor.getActorType())
                || MtmWorkflowStepUserActor.ACTOR_TYPE_REPORT_TO_OF_ACTION_TAKER.equals(dynamicActor.getActorType()) ){
              actorTypeList.add(dynamicActor.getActorType() + dynamicActor.getActorID() + "_" + dynamicActor.getPermission());
            } else {
              actorTypeList.add(dynamicActor.getActorType() + "_" + dynamicActor.getPermission());
            }
          }
        }
        userRecords = (String[]) userRecordList.toArray(userRecords);
        userRoles = (String[]) userRoleList.toArray(userRoles);
        userGroups = (String[]) userGroupList.toArray(userGroups);
        actorTypes = (String[]) actorTypeList.toArray(actorTypes);
      } else {
        userRecords = (String[])RequestUtils.lookup(pageContext, formTag.getBeanName(), userListName, null);
        userGroups = (String[])RequestUtils.lookup(pageContext, formTag.getBeanName(), groupListName, null);
        userRoles = (String[])RequestUtils.lookup(pageContext, formTag.getBeanName(), roleListName, null);
        actorTypes = (String[])RequestUtils.lookup(pageContext, formTag.getBeanName(), actorListName, null);
      }
			if(Utility.isEmpty(userRecords) && Utility.isEmpty(userGroups) && Utility.isEmpty(userRoles) && !Utility.isEmpty(actorTypes)&&actorTypes.length==1){
        String[] types=actorTypes[0].split("_");
        if(WorkflowStep.NOTIFY_ALL_TASK_COMPLETED_BY_SYSTEM.equals(types[0])){
          actorTypes=null;
        }
      }

      Map permissionMap = new TreeMap();
      if (!Utility.isEmpty(this.permissionType)) {
        for(int i = 0 ; !Utility.isEmpty(userRecords)&& i < userRecords.length ; i++){
          log.debug("The userRecord ID" + userRecords[i].substring(0,userRecords[i].indexOf("_")) +"The UserRecord ID :::" + userRecords[i].substring(userRecords[i].indexOf("_")+1, userRecords[i].length()));
          permissionMap.put("U"+userRecords[i].substring(0,userRecords[i].indexOf("_")),userRecords[i].substring(userRecords[i].indexOf("_")+1, userRecords[i].length()));
        }
        for(int i = 0 ; !Utility.isEmpty(userGroups)&& i < userGroups.length ; i++){
          permissionMap.put("G"+userGroups[i].substring(0,userGroups[i].indexOf("_")),userGroups[i].substring(userGroups[i].indexOf("_")+1, userGroups[i].length()));
        }
        for(int i = 0 ; !Utility.isEmpty(userRoles)&& i < userRoles.length ; i++){
          permissionMap.put("R"+userRoles[i].substring(0,userRoles[i].indexOf("_")),userRoles[i].substring(userRoles[i].indexOf("_")+1, userRoles[i].length()));
        }
        for(int i = 0 ; !Utility.isEmpty(actorTypes)&& i < actorTypes.length ; i++){
          permissionMap.put(actorTypes[i].substring(0,actorTypes[i].indexOf("_")),actorTypes[i].substring(actorTypes[i].indexOf("_")+1, actorTypes[i].length()));
        }
      } else {
        for(int i = 0 ; !Utility.isEmpty(userRecords)&& i < userRecords.length ; i++){
          permissionMap.put("U"+userRecords[i],"");
        }
        for(int i = 0 ; !Utility.isEmpty(userGroups)&& i < userGroups.length ; i++){
          permissionMap.put("G"+userGroups[i],"");
        }
        for(int i = 0 ; !Utility.isEmpty(userRoles)&& i < userRoles.length ; i++){
          permissionMap.put("R"+userRoles[i],"");
        }
        for(int i = 0 ; !Utility.isEmpty(actorTypes)&& i < actorTypes.length ; i++){
          permissionMap.put(actorTypes[i],"");
        }
      }

      StringBuffer allPermissionData = new StringBuffer();
      StringBuffer userNoPermissionData = new StringBuffer();
      StringBuffer groupNoPermissionData = new StringBuffer();
      StringBuffer roleNoPermissionData = new StringBuffer();
      StringBuffer otherNoPermissionData = new StringBuffer();

      //get all users name
      for(int i = 0 ; i < allUserList.size() ; i++){
        UserRecord userRecord = (UserRecord)allUserList.get(i);
        StringBuffer data = new StringBuffer();
        if(permissionMap.containsKey("U"+userRecord.getID())){
          if (Utility.isEmpty(this.permissionType)) {
            data.append(userRecord.getID()).append(DELIMITER_FIELD).append(userRecord.getFullName()).append(DELIMITER_FIELD).append("U").append(DELIMITER_FIELD).append("N").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          } else {
            data.append(userRecord.getID()).append(DELIMITER_FIELD).append(userRecord.getFullName()).append(DELIMITER_FIELD).append("U").append(DELIMITER_FIELD).append((String)permissionMap.get("U"+userRecord.getID())).append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          }
          allPermissionData.append(data);
        }else{
          data.append(userRecord.getID()).append(DELIMITER_FIELD).append(userRecord.getFullName()).append(DELIMITER_FIELD).append("U").append(DELIMITER_FIELD).append("N").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          userNoPermissionData.append(data);
        }
        //allUserString.append(userRecord.getID()).append(DELIMITER_FIELD).append(userRecord.getFullName()).append(DELIMITER_FIELD).append("U").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("N").append(DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
      }

      //get all groups name
      for(int i = 0 ; i < allGroupList.size() ; i++){
        UserGroup userGroup = (UserGroup)allGroupList.get(i);
        StringBuffer data = new StringBuffer();
        if(permissionMap.containsKey("G"+userGroup.getID())){
          if (Utility.isEmpty(this.permissionType)) {
            data.append(userGroup.getID()).append(DELIMITER_FIELD).append(userGroup.getGroupName()).append(DELIMITER_FIELD).append("G").append(DELIMITER_FIELD).append("N").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          } else {
            //data.append(userGroup.getID()).append(DELIMITER_FIELD).append(userGroup.getGroupName()).append(DELIMITER_FIELD).append("G").append(DELIMITER_FIELD).append("N").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
            data.append(userGroup.getID()).append(DELIMITER_FIELD).append(userGroup.getGroupName()).append(DELIMITER_FIELD).append("G").append(DELIMITER_FIELD).append((String)permissionMap.get("G"+userGroup.getID())).append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          }
          allPermissionData.append(data);
        }else{
          data.append(userGroup.getID()).append(DELIMITER_FIELD).append(userGroup.getGroupName()).append(DELIMITER_FIELD).append("G").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("N").append(DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          groupNoPermissionData.append(data);
        }
        //        allGroupString.append(userGroup.getID()).append(DELIMITER_FIELD).append(userGroup.getGroupName()).append(DELIMITER_FIELD).append("G").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("N").append(DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
      }

      //get all roles name
      for(int i = 0 ; i < allRoleList.size() ; i++){
        UserRole userRole = (UserRole)allRoleList.get(i);
        StringBuffer data = new StringBuffer();

        if(permissionMap.containsKey("R"+userRole.getID())){
          if (Utility.isEmpty(this.permissionType)) {
            data.append(userRole.getID()).append(DELIMITER_FIELD).append(userRole.getRoleName()).append(DELIMITER_FIELD).append("R").append(DELIMITER_FIELD).append("N").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          } else {
            data.append(userRole.getID()).append(DELIMITER_FIELD).append(userRole.getRoleName()).append(DELIMITER_FIELD).append("R").append(DELIMITER_FIELD).append((String)permissionMap.get("R"+userRole.getID())).append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          }
          allPermissionData.append(data);
        }else{
          data.append(userRole.getID()).append(DELIMITER_FIELD).append(userRole.getRoleName()).append(DELIMITER_FIELD).append("R").append(DELIMITER_FIELD).append("N").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          roleNoPermissionData.append(data);
        }
        //        allRoleString.append(userRole.getID()).append(DELIMITER_FIELD).append(userRole.getRoleName()).append(DELIMITER_FIELD).append("R").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("N").append(DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
      }

      // TODO: Retrieve the otherList in attribute
      Locale locale = sessionContainer.getSessionLocale();
      WorkflowRetrievalManager retrievalManager = new WorkflowRetrievalManager(sessionContainer, conn);

      String[][] ACTOR_TYPE_MAP = (String[][])pageContext.getRequest().getAttribute("ACTOR_TYPE_MAP");

      if ( !Utility.isEmpty(ACTOR_TYPE_MAP) && ACTOR_TYPE_MAP.length > 0 ) {
        for ( int i=0 ; i < ACTOR_TYPE_MAP.length ; i ++ ) {
          allOtherList.add(new String[]{ACTOR_TYPE_MAP[i][1], ACTOR_TYPE_MAP[i][0]});
          if(!this.enableOthers){
            break;
          }
        }
      }

      String parentStepID = pageContext.getRequest().getParameter("parentStepID");
//			if (!Utility.isEmpty(parentStepID)) {
//				List parentStepNameList = retrievalManager.getSuperStepNameListByWorkflowStepID(new Integer(parentStepID));
//				for ( int i = 0; i < parentStepNameList.size(); i++ ) {
//					String[] stepName = (String[])parentStepNameList.get(i);
//					allOtherList.add(new String[]{stepName[0], stepName[1]});
//				}
//			}

      //get the special actor
      for(int i = 0 ; i < allOtherList.size() ; i++){
        String actor[] = (String[])allOtherList.get(i);
        StringBuffer data = new StringBuffer();
        if(permissionMap.containsKey(actor[0])){
          if (Utility.isEmpty(this.permissionType)) {
            data.append(actor[0]).append(DELIMITER_FIELD).append(actor[1]).append(DELIMITER_FIELD).append("O").append(DELIMITER_FIELD).append("N").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          } else {
            data.append(actor[0]).append(DELIMITER_FIELD).append(actor[1]).append(DELIMITER_FIELD).append("O").append(DELIMITER_FIELD).append((String)permissionMap.get(actor[0])).append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          }
          allPermissionData.append(data);
        }else{
             data.append(actor[0]).append(DELIMITER_FIELD).append(actor[1]).append(DELIMITER_FIELD).append("O").append(DELIMITER_FIELD).append("N").append(DELIMITER_FIELD+DELIMITER_FIELD+DELIMITER_FIELD).append("-1").append(DELIMITER_ENTRY);
          otherNoPermissionData.append(data);
        }
      }

      out.println("<table width=\"100%\" border=\"0\" cellpadding=\"1\" cellspacing=\"0\">");
      if (!Utility.isEmpty(this.postFix)) {
        out.println("  <input type=\"hidden\" name=\"permissionType_" + this.postFix + "\" value=\"" + this.getPermissionType() + "\">");
        out.println("  <input type=\"hidden\" name=\"userNoPermissionData_" + this.postFix + "\" value=\"" + userNoPermissionData.toString() + "\">");
        out.println("  <input type=\"hidden\" name=\"groupNoPermissionData_" + this.postFix + "\" value=\"" + groupNoPermissionData.toString() + "\">");
        out.println("  <input type=\"hidden\" name=\"roleNoPermissionData_" + this.postFix + "\" value=\"" + roleNoPermissionData.toString() + "\">");
        //if(this.enableOthers){
        out.println("  <input type=\"hidden\" name=\"otherNoPermissionData_" + this.postFix + "\" value=\"" + otherNoPermissionData.toString() + "\">");
        //}
        out.println("  <input type=\"hidden\" name=\"allPermissionData_" + this.postFix + "\" value=\"" + allPermissionData.toString() + "\">");
        out.println("  <input type=\"hidden\" name=\"ownerLimit_" + this.postFix + "\" value=\"" + this.ownerLimit + "\">");
      } else {
        out.println("  <input type=\"hidden\" name=\"permissionType\" value=\"" + this.getPermissionType() + "\">");
        out.println("  <input type=\"hidden\" name=\"userNoPermissionData\" value=\"" + userNoPermissionData.toString() + "\">");
        out.println("  <input type=\"hidden\" name=\"groupNoPermissionData\" value=\"" + groupNoPermissionData.toString() + "\">");
        out.println("  <input type=\"hidden\" name=\"roleNoPermissionData\" value=\"" + roleNoPermissionData.toString() + "\">");
        //if(this.enableOthers){
        out.println("  <input type=\"hidden\" name=\"otherNoPermissionData\" value=\"" + otherNoPermissionData.toString() + "\">");
        //}
        out.println("  <input type=\"hidden\" name=\"allPermissionData\" value=\"" + allPermissionData.toString() + "\">");
        out.println("  <input type=\"hidden\" name=\"ownerLimit\" value=\"" + this.ownerLimit + "\">");
      }

     
      out.println("  <tr>");
      out.println("    <td width=\"450\" valign=\"top\">");
      // Left Panel Begin
      out.println("      <table width=\"450\" border=\"0\" cellpadding=\"1\" cellspacing=\"0\">");
      if(showPermissionTitle){
        out.println("        <tr>");
        out.println("          <td width=\"450\" align=\"center\"><b><u>" + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "setup.label.user_permission_list") + "</u></b></td>");
        out.println("        </tr>");
      }
      out.println("        <tr>");
      if (!Utility.isEmpty(this.postFix)) {
        out.println("          <td width=\"450\" valign=\"top\" height=\"" + (formTag.getTextOnly() ? "300" : "200") + "\"><div id=\"permissionDiv" + this.postFix +  "\" class=\"form-style-2-optionsDiv\" style=\"width:448;height:" + (formTag.getTextOnly() ? "300" : "200") + "px;background-color:" + (formTag.getTextOnly() ? "#EEEEEE" : "#FFFFFF") + ";layer-background-color:" + (formTag.getTextOnly() ? "#EEEEEE" : "#FFFFFF") + ";\"></div></td>");
      } else {
        out.println("          <td width=\"450\" valign=\"top\" height=\"" + (formTag.getTextOnly() ? "300" : "200") + "\"><div id=\"permissionDiv\" class=\"form-style-2-optionsDiv\" style=\"width:448;height:" + (formTag.getTextOnly() ? "300" : "200") + "px;background-color:" + (formTag.getTextOnly() ? "#EEEEEE" : "#FFFFFF") + ";layer-background-color:" + (formTag.getTextOnly() ? "#EEEEEE" : "#FFFFFF") + ";\"></div></td>");
      }
      out.println("        </tr>");
      if (!formTag.getTextOnly()) {
        out.println("        <tr>");
        out.println("          <td align=\"left\" valign=\"middle\" height=\"25\">");
        out.println("            <table width=\"100%\" border=\"0\" cellpadding=\"1\" cellspacing=\"0\">");
        out.println("              <tr>");
        out.println("                <td width=\"35%\" valign=\"bottom\">");
        if (!Utility.isEmpty(this.postFix)) {
          out.println("                  <select name=\"subjectType_" + this.postFix + "\" onchange=\"changeSubjectMenuForPostFix(this.form," + this.postFix + ")\">");
        } else {
          out.println("                  <select name=\"subjectType\" onchange=\"changeSubjectMenu(this.form)\">");
        }
        out.println("                    <option value=\"R\">" + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "setup.label.subject_type_R") + "</option>");
        out.println("                    <option value=\"G\">" + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "setup.label.subject_type_G") + "</option>");
        out.println("                    <option value=\"U\">" + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "setup.label.subject_type_U") + "</option>");
        if(Utility.isEmpty(this.isAssignOwner) || !this.isAssignOwner.equalsIgnoreCase("true")){
        out.println("                    <option value=\"O\">" + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "setup.label.special_actor") + "</option>");
        }
        out.println("                  </select>");
        out.println("                </td>");
        out.println("                <td align=\"right\" valign=\"bottom\">");
        out.println("                <div style=\"float:right;\">");
        if (!Utility.isEmpty(this.postFix)) {
          out.println("                  "+TagUtil.renderStandardButton(pageContext, "workflow.applet.add", "return(addSubjectForPostFix(" + this.postFix + "))", null));
          out.println("                  "+TagUtil.renderStandardButton(pageContext, "contact.label.remove", "return(delSubject(" + this.postFix + "))", null));
        } else {
          out.println("                  "+TagUtil.renderStandardButton(pageContext, "workflow.applet.add", "return addSubject()", null));
          out.println("                  "+TagUtil.renderStandardButton(pageContext, "contact.label.remove", "return delSubject()", null));
        }
        out.println("                  </div>");
        out.println("                </td>");
        out.println("              </tr>");
        out.println("            </table>");
        out.println("          </td>");
        out.println("        </tr>");
        out.println("        <tr>");
        out.println("          <td>");
        if (!Utility.isEmpty(this.postFix)) {
          out.println("            <select name=\"subjectList_" + this.postFix + "\" size=\"8\" style=\"width:450px\"  ondblclick =\"return(addSubjectForPostFix(" + this.postFix + "))\" multiple></select>");
        } else {
          out.println("            <select name=\"subjectList\" size=\"8\" style=\"width:450px\"  ondblclick =\"return(addSubject())\" multiple></select>");
        }
        out.println("          </td>");
        out.println("        </tr>");
      }
      out.println("      </table>");
      // Left Panel End
      out.println("    </td>");
      if(!Utility.isEmpty(this.permissionType)){
        out.println("    <td width=\"20\">&nbsp;</td>");
        out.println("    <td valign=\"top\">");
        // Right Panel Begin
        out.println("<script language=\"Javascript\">");
        out.println("<!--");
        out.println("//Permission Labels");
        out.println("var permLabel = new Array();");
        for (int i = 0; i < this.permissionType.length(); i++) {
          out.println("permLabel['"+this.permissionType.charAt(i)+"'] = '"+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), labelPrefix+this.permissionType.charAt(i))+"';");
        }
        out.println("//-->");
        out.println("</script>");
        out.println("      <table width=\"100%\" border=\"0\" cellpadding=\"1\" cellspacing=\"0\">");
        out.println("        <tr>");
        out.println("          <td>");
        out.println("            <div id=\"permDiv\">");
        out.println("            <table cellpadding=\"0\" cellspacing=\"2\" border=\"0\">");
        out.println("              <tr>");
        out.println("                <td align=\"center\" width=\"120\"><b>" + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "setup.label.access_right") + "</b></td>");
        if (formTag.getTextOnly()) {
          out.println("                <td align=\"center\" width=\"80\"><b>" + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "setup.label.allow") + "</b></td>");
          out.println("                <td align=\"center\" width=\"80\"><b>" + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "setup.label.deny") + "</b></td>");
        } else {
          out.println("                <td align=\"center\" width=\"80\"><b><a href=\"#\" onclick=\"return togglePermissionAllowAll()\">" + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "setup.label.allow") + "</a></b></td>");
          out.println("                <td align=\"center\" width=\"80\"><b><a href=\"#\" onclick=\"return togglePermissionDenyAll()\">" + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "setup.label.deny") + "</a></b></td>");
        }
        out.println("                <td align=\"center\" width=\"20\">&nbsp;</td>");
        out.println("              </tr>");
        out.println("              <tr>");
        out.println("                <td colspan=\"4\" class=\"blackline\"><img src='" + WebUtil.getImage(pageContext.getRequest(), "LayoutSpacer.gif")+"' height='1px' width='1px'/></td>");
        out.println("              </tr>");
        // Loop for permission settings.
        for (int i = 0; i < this.permissionType.length(); i++) {
          String permissionOne = this.permissionType.substring(i, i+1);
        

          out.println("              <tr>");
          out.println("                <td align=\"left\">" + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), this.labelPrefix + permissionOne) + "</td>");
          if (!Utility.isEmpty(this.postFix)) {
            if (formTag.getTextOnly()) {
              out.println("                <td align=\"center\"><input type=\"checkbox\" name=\"permission_" + this.postFix + "_" + this.permissionType.charAt(i) + "\" value=\"Y\" onclick=\"return(false)\"></td>");
              out.println("                <td align=\"center\"><input type=\"checkbox\" name=\"permission_" + this.postFix + "_" + Character.toLowerCase(this.permissionType.charAt(i)) + "\" value=\"Y\" onclick=\"return(false)\"></td>");
            } else {
              out.println("                <td align=\"center\"><input type=\"checkbox\" name=\"permission_" + this.postFix + "_" + this.permissionType.charAt(i) + "\" value=\"Y\" onclick=\"return checkPermission(this)\"></td>");
              out.println("                <td align=\"center\"><input type=\"checkbox\" name=\"permission_" + this.postFix + "_" + Character.toLowerCase(this.permissionType.charAt(i)) + "\" value=\"Y\" onclick=\"return checkPermission(this)\"></td>");
            }
          } else {
            if (formTag.getTextOnly()) {
              out.println("                <td align=\"center\"><input type=\"checkbox\" name=\"permission_" + this.permissionType.charAt(i) + "\" value=\"Y\" onclick=\"return(false)\"></td>");
              out.println("                <td align=\"center\"><input type=\"checkbox\" name=\"permission_" + Character.toLowerCase(this.permissionType.charAt(i)) + "\" value=\"Y\" onclick=\"return(false)\"></td>");
            } else {
              out.println("                <td align=\"center\"><input type=\"checkbox\" name=\"permission_" + this.permissionType.charAt(i) + "\" value=\"Y\" onclick=\"return checkPermission(this)\"></td>");
              out.println("                <td align=\"center\"><input type=\"checkbox\" name=\"permission_" + Character.toLowerCase(this.permissionType.charAt(i)) + "\" value=\"Y\" onclick=\"return checkPermission(this)\"></td>");
            }
          }
          out.println("                <td align=\"center\" width=\"20\">&nbsp;</td>");
          out.println("              </tr>");
          out.println("              <tr>");
          out.println("                <td colspan=\"4\" class=\"blackline\"><img src='" + WebUtil.getImage(pageContext.getRequest(), "LayoutSpacer.gif")+"' height='1px' width='1px'/></td>");
          out.println("              </tr>");
        }
        out.println("        <tr>");
        out.println("          <td colsoan=\"4\"><img src='" + WebUtil.getImage(pageContext.getRequest(), "LayoutSpacer.gif")+"' height='4' width='1'/></td>");
        out.println("        </tr>");
        if (!formTag.getTextOnly()) {
          out.println("<tr><td colspan=\"4\">");
          if (!Utility.isEmpty(this.postFix)) {
         
            out.println("                  <div style=\"float:right;margin-left:10px;\">");
            out.println("                  "+TagUtil.renderStandardButton(pageContext, "common.label.update", "return(updatePermission(" + this.postFix + "))", null));
            out.println("                  </div>");
          } else {
            
            out.println("                  <div style=\"float:right;margin-left:10px;\">");
            out.println("                  "+TagUtil.renderStandardButton(pageContext, "common.label.update", "return(updatePermission())", null));
            out.println("                  </div>");
          }
          out.println("</td></tr>");
        }
        
        out.println("            </table>");
        out.println("            </div>");
        out.println("          </td>");
        out.println("        </tr>");
     
        out.println("                  <input type=\"hidden\" name=\"startDate\" value=\"\">");
        out.println("                  <input type=\"hidden\" name=\"endDate\" value=\"\">");
        
        out.println("      </table>");
        // Right Panel End
        out.println("    </td>");
      }
      out.println("  </tr>");
      out.println("</table>");
    }catch(Exception ex){
      log.debug(ex.getMessage(), ex);
    }
    return sb.toString();
  }

  protected void init() throws ApplicationException {
    sessionContainer = (SessionContainer)this.pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    contextPath = (String)this.pageContext.getServletContext().getAttribute(GlobalConstant.CONTEXT_PATH_KEY);

    if ( !validateTag() ){
      throw new IllegalArgumentException();
    }

  }

}
